<?php
/*
 * @Author: your name
 * @Date: 2021-12-07 09:50:02
 * @LastEditTime: 2022-02-19 19:14:49
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \property\app\Http\Controllers\find_shop\User.php
 */

namespace App\Http\Controllers\daily_partTime;

use Illuminate\Support\Facades\Request;
use  App\Http\Controllers\redis\RedisController as Redis;
use  App\Models\daily_partTime\User as UserDb;

class User extends BaseController
{
    private $prefix  = "";

    public function __construct()
    {
        $this->prefix  = PARTTIME_LOGIN_REDIS_KEY;
    }

    //微信小程序登录
    public function userLoginWechat()
    {
        // echo __REDIS_HOST__;
        // $this->$prefix;
        if (Request::has('formData') && Request::has('js_code')) {
            $formData = Request::input('formData');
            $js_code =  Request::input('js_code');
            if (isset($formData['openid'])) {
                return $this->create(100, '非法请求', [], 500);
            }
            $durl = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . __PARTIMEWXAPPID__ . '&secret=' . __PARTIMEWXAPPSECRET__ . '&js_code=' . $js_code . '&grant_type=authorization_code';
            $res = json_decode(http_request($durl), true);
            if (isset($res['openid'])) {
                $formData['openid'] = $res['openid'];
            } else {
                return  $this->create(100, '微信调取登录失败');
            }
            $formData['source'] = 'Wechat';
            $formDataStr = insertUpdatedStr($formData);
            $res = UserDb::insertUpdated($formDataStr);
            if ($res) {
                $token = md5(create_uuid('*' . $formData['openid'] . '*'));
                Redis::hMset($this->prefix . $token,   ['openid' => $formData['openid']], 7 * 24 * 3600, ['RedisDB' => $this->dbNumber]);          //数据库12保存登录信息  一个星期后过期
                $fd = Request::input('fd');
                $is_customer = 1;    //为客户判断是否客服登录
                if( $fd ){
                    $is_customer =   $this->onBind( $fd,$token);
                }
                return   $this->create(200, '登录成功', ['userInfo' => $formData,'is_customer'=> $is_customer,'token' => $token]);
            } else {
                return   $this->create(100, '登录失败');
            }
        } else {
            return   $this->create(100, '非法请求', 500);
        }
    }
    //头条小程序登录
    public function userLoginToutiao()
    {
        if (Request::has('formData') && Request::has('js_code')) {
            $formData = Request::input('formData');
            $js_code =  Request::input('js_code');
            $fd = Request::input('fd');
            if (isset($formData['openid'])) {
                return $this->create(100, '非法请求', [], 500);
            }
            $durl = 'https://developer.toutiao.com/api/apps/jscode2session?appid=' . __PARTIMETTAPPID__ . '&secret=' . __PARTIMETTAPPSECRET__ . '&code=' . $js_code;
            $res = json_decode(http_request($durl), true);
            if (isset($res['openid'])) {
                $formData['openid'] = $res['openid'];
            } else {
                return  $this->create(100, '头条调取登录失败');
            }
            $formData['source'] = 'Toutiao';
            $formDataStr = insertUpdatedStr($formData);
            $res = UserDb::insertUpdated($formDataStr);
            if ($res) {
                $token = md5(create_uuid('*' . $formData['openid'] . '*'));
                Redis::hMset($this->prefix . $token, ['openid' => $formData['openid']], 7 * 24 * 3600, ['RedisDB' => $this->dbNumber]);          //数据库12保存登录信息  一个星期后过期
                $is_customer = 1;
                if( $fd ){
                    $this->onBind( $fd,$token);
                }

                return   $this->create(200, '登录成功', ['userInfo' => $formData, 'is_customer'=> $is_customer,'token' => $token]);
            } else {
                return   $this->create(100, '登录失败');
            }
        } else {
            return   $this->create(100, '非法请求', 500);
        }
    }


    public function checkToken($die = true)
    {
        $header =  $_SERVER;
        if (!isset($header['TOKEN'])) {
            return   abort(500);
        } else {
            $token =  $_SERVER['TOKEN'];
            $key = $this->prefix . $token;
            if ($token && Redis::existSKey($key, ['RedisDB' => $this->dbNumber])) {
                Redis::expire($key, 7 * 24 * 3600, ['RedisDB' => $this->dbNumber]);          //重置登录时间
                $fd = Request::input('fd');
                $is_customer = 1;
                if( $fd ){
                    $is_customer =   $this->onBind( $fd);
                }
                return $die ? $this->create(200, '后台还在登录中。。。', ['is_customer'=>$is_customer]) : true;
            } else {
                return $die ? $this->create(100, '登录已过期') : false;
            }
        }
    }

    public function loginOut()
    {
        $token = $_SERVER['TOKEN'];
        if ($token) {
            $key = $this->prefix . $token;
            if (Redis::existSKey($key, ['RedisDB' => $this->dbNumber])) {
                Redis::del($key, ['RedisDB' => $this->dbNumber]);
            }
        }
        return $this->create(200, '退出成功');
    }


    public function checkCustomer()
    {
       
            $loginMsg = $this->getLoginAllMsg();
            $this->onBind(Request::input('fd'),null,$loginMsg);
            return $this->create(200, '查询成功', ['is_customer' => $loginMsg['is_customer']]);

    }
  


    public function onBind($fd,$token = null, $loginMsg = null)
    {
        $loginMsg =$loginMsg?$loginMsg:$this->getLoginAllMsg($token);
        
        $is_customer   = $loginMsg['is_customer'];
        Redis::hMset($this->online_key,[$fd=>$loginMsg['openid']],['RedisDB' => $this->dbNumber]);    //绑定当前在线fd

        if($is_customer == 1){    //1为客户
             Redis::sAdd($this->customRedisKey.$loginMsg['openid'], $fd,['RedisDB' => $this->dbNumber] );        //当前openid绑定的fd
        }else if($is_customer == 0 ){                                                    //0为客服  客服绑定集合 
             Redis::hMset( $this->service_redis , [$fd => $loginMsg['openid']  ],['RedisDB' => $this->dbNumber]);                   //绑定用户openid
        } 
        return  $is_customer;
    }


    public function getUserMessage(){
        if(Request::has('user_id')){
            return $this->create(200,'查询成功', redis_mysql_selone_return('daily_parttime_user',Request::input('user_id'))) ;
        }
    }

    // public function sss
}
